package net.ufrog.common;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 链表接口
 *
 * @author ultrafrog, ufrog.net@gmail.com
 * @version 0.1, 2017-03-25
 * @since 0.1
 */
public interface Link<ID> {

    /**
     * 读取编号
     *
     * @return 编号
     */
    ID getId();

    /**
     * 读取下位编号
     *
     * @return 下位编号
     */
    ID getNextId();

    /**
     * 链表排序
     *
     * @param links 原对象列表
     * @param <T> 对象泛型
     * @return 排序后对象列表
     */
    static <T extends Link> List<T> sort(List<T> links) {
        String lastKey = "_last";
        List<T> list = new ArrayList<>(links.size());
        Map<?, T> mapping = links.stream().collect(Collectors.toMap(link -> (link.getNextId() == null ? lastKey : link.getNextId()), link -> link));

        for (T current = mapping.get(lastKey); current != null; current = mapping.get(current.getId())) {
            list.add(0, current);
        }
        if (Logger.isDebugEnabled()) Logger.debug("link order: %s", list.stream().map(link -> String.valueOf(link.getId())).collect(Collectors.joining(" -> ")));
        return list;
    }
}
